package com.jf3q.security.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;

import java.io.Serializable;
import java.security.Permission;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 用户表
 * @TableName edu_acl_user
 */
@TableName(value ="edu_acl_user")
@Data
public class EduAclUser implements Serializable , UserDetails {
    /**
     * 会员id
     */
    @TableId
    private String id;

    /**
     * 微信openid
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 昵称
     */
    private String nickName;

    /**
     * 用户头像
     */
    private String salt;

    /**
     * 用户签名
     */
    private String token;

    /**
     * 逻辑删除 1（true）已删除， 0（false）未删除
     */
    private Byte isDeleted;

    /**
     * 创建时间
     */
    private Date eduCreate;

    /**
     * 更新时间
     */
    private Date eduModified;
    @TableField(exist = false)
    private List<EduAclRole> roles;

    @TableField(exist = false)
    private static final long serialVersionUID = 1L;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (EduAclRole role : roles) {
            List<EduAclPermission> permissions = role.getPermissions();
            for (EduAclPermission permission : permissions) {
                if (!ObjectUtils.isEmpty(permission.getPermissionValue())) {
                    SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission.getPermissionValue());
                    list.add(authority);
                }
            }
        }
        return list;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {

        if (isDeleted==1) {
            return false;
        }else{
            return true;
        }

    }
}
